<template>
    <div>
        <a-table :columns="columns" :data-source="triggerData" :pagination="false" row-key="_rowKey">
            <template #bodyCell="{ column, record, index }">
                <template v-if="column.dataIndex === 'name'">
                    <a-input v-model:value="record.name" placeholder="触发器名" />
                </template>
                <template v-if="column.dataIndex === 'event_insert'">
                    <a-checkbox v-model:checked="record.event_insert" />
                </template>
                <template v-if="column.dataIndex === 'event_update'">
                    <a-checkbox v-model:checked="record.event_update" />
                </template>
                <template v-if="column.dataIndex === 'event_delete'">
                    <a-checkbox v-model:checked="record.event_delete" />
                </template>
                <template v-if="column.dataIndex === 'actions'">
                    <a-space>
                        <a-button type="link" danger @click="removeRow(index)">删除</a-button>
                        <a-button v-if="index === triggerData.length - 1" type="link" @click="addRow">新增</a-button>
                    </a-space>
                </template>
            </template>
        </a-table>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

const props = defineProps<{
    table_name: string
    triggers?: any[]
}>()
const emits = defineEmits(['update:triggers'])

const columns = [
    { title: '名', dataIndex: 'name' },
    { title: '触发', dataIndex: 'trigger' },
    { title: '插入', dataIndex: 'event_insert' },
    { title: '更新', dataIndex: 'event_update' },
    { title: '删除', dataIndex: 'event_delete' },
    { title: '操作', dataIndex: 'actions' }
]

const triggerData = ref<any[]>([])

function addRow() {
    triggerData.value.push({
        _rowKey: Date.now() + Math.random(),
        name: '',
        trigger: '',
        event_insert: false,
        event_update: false,
        event_delete: false
    })
}

function removeRow(index: number) {
    triggerData.value.splice(index, 1)
    if (triggerData.value.length === 0) {
        addRow()
    }
}

watch(
    () => props.triggers,
    (triggers) => {
        if (triggers && triggers.length > 0) {
            triggerData.value = triggers.map((t, i) => ({ ...t, _rowKey: i + '-' + Date.now() }))
        } else {
            triggerData.value = []
            addRow()
        }
    },
    { immediate: true, deep: true }
)

watch(triggerData, (val) => {
    emits('update:triggers', val)
}, { deep: true })
</script>
